/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.live.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.live.domain.Live;
import com.fzhucc.modules.live.domain.dto.LiveAddDto;
import com.fzhucc.modules.live.domain.dto.LiveEditDto;
import com.fzhucc.modules.liveCp.domain.LiveCp;
import com.fzhucc.modules.liveCp.domain.dto.LiveCpDto;
import com.fzhucc.modules.liveCp.repository.LiveCpRepository;
import com.fzhucc.modules.liveCp.service.mapstruct.LiveCpMapper;
import com.fzhucc.modules.liveRecordLog.domain.LiveRecordLog;
import com.fzhucc.modules.liveRecordLog.repository.LiveRecordLogRepository;
import com.fzhucc.modules.notice.domain.Notice;
import com.fzhucc.modules.notice.domain.dto.NoticeDto;
import com.fzhucc.modules.notice.domain.dto.NoticeQueryCriteria;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoDto;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.dto.UserDto;
import com.fzhucc.utils.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.live.repository.LiveRepository;
import com.fzhucc.modules.live.domain.dto.LiveDto;
import com.fzhucc.modules.live.domain.dto.LiveQueryCriteria;
import com.fzhucc.modules.live.service.mapstruct.LiveMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-04-29
 **/
@Service
@RequiredArgsConstructor
public class LiveService {

    private final LiveRepository liveRepository;

    private final LiveCpRepository liveCpRepository;

    private final LiveRecordLogRepository liveRecordLogRepository;
    private final LiveMapper liveMapper;

    private final LiveCpMapper liveCpMapper;

    private final UserRepository userRepository;

    private final FenRecordLogService fenRecordLogService;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.zb}")
    public String zb;

    //根据不同设置不同的部门查看
    public String setCriteria(LiveQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    public Map<String, Object> queryAll(LiveQueryCriteria criteria, Pageable pageable) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
                if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                    //TODO 即查询参数有参数  省总账号查具体模糊查询
                    String[] orgAreas = criteria.getOrgAreas();
                    criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
                }
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                //传参要查的 orgArea
                String csOrgArea = orgAreas[orgAreas.length - 1];
                //登录用户的 orgArea
                String dlOrgArea = criteria.getOrgArea();
                if (dlOrgArea == null) { //表示省总
                    criteria.setOrgArea(csOrgArea);
                } else {
                    //不是省总  登录的 存在  传进来的全部 则可以 否则则使用登录的
                    String[] split = dlOrgArea.split(";");
                    if (split.length == 1) {
                        //表示为省
                        if (split[0].equals(all)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            //其他省 则 传进来的第一个和这个省一致才返回数据
                            String orgArea = orgAreas[0];
                            if (split[0].equals(orgArea)) {
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 2) {
                        //例 ： 福建省;福州市;
                        String s = split[1];
                        if (orgAreas.length == 3) {
                            //福建省;福州市;马尾区;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                        if (orgAreas.length == 2) {
                            //福建省;福州市;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 3) {
                        //例 ： 福建省;福州市;马尾区;  相符就查马尾区  不相符就查登录用户的区域
                        String s = split[2];
                        if (s.equals(csOrgArea)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            criteria.setOrgArea(dlOrgArea);
                        }
                    }
                }
            }
        }
        criteria.setIsDelete(0);
        Page<Live> page = liveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LiveDto> map = page.map(liveMapper::toDto);
        List<LiveDto> list = map.getContent();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                LiveDto liveDto = list.get(i);
                String orgArea = liveDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    liveDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    liveDto.setOrgAreas(array);
                }

                List<LiveCp> list2 = liveCpRepository.findByLiveId(liveDto.getId());
                List<LiveCpDto> liveCpDtos = liveCpMapper.toDto(list2);
                liveDto.setListCpDto(liveCpDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAllh5(LiveQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(zb);
        } catch (Exception e) {

        }

        LiveRecordLog liveRecordLog = new LiveRecordLog();
        liveRecordLogRepository.save(liveRecordLog);

        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
                if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                    //TODO 即查询参数有参数  省总账号查具体模糊查询
                    String[] orgAreas = criteria.getOrgAreas();
                    criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
                }
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                //传参要查的 orgArea
                String csOrgArea = orgAreas[orgAreas.length - 1];
                //登录用户的 orgArea
                String dlOrgArea = criteria.getOrgArea();
                if (dlOrgArea == null) { //表示省总
                    criteria.setOrgArea(csOrgArea);
                } else {
                    //不是省总  登录的 存在  传进来的全部 则可以 否则则使用登录的
                    String[] split = dlOrgArea.split(";");
                    if (split.length == 1) {
                        //表示为省
                        if (split[0].equals(all)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            //其他省 则 传进来的第一个和这个省一致才返回数据
                            String orgArea = orgAreas[0];
                            if (split[0].equals(orgArea)) {
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 2) {
                        //例 ： 福建省;福州市;
                        String s = split[1];
                        if (orgAreas.length == 3) {
                            //福建省;福州市;马尾区;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                        if (orgAreas.length == 2) {
                            //福建省;福州市;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 3) {
                        //例 ： 福建省;福州市;马尾区;  相符就查马尾区  不相符就查登录用户的区域
                        String s = split[2];
                        if (s.equals(csOrgArea)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            criteria.setOrgArea(dlOrgArea);
                        }
                    }
                }
            }
        }
        criteria.setIsDelete(0);
        Page<Live> page = liveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LiveDto> map = page.map(liveMapper::toDto);
        List<LiveDto> list = map.getContent();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                LiveDto liveDto = list.get(i);
                String orgArea = liveDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    liveDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    liveDto.setOrgAreas(array);
                }

                List<LiveCp> list2 = liveCpRepository.findByLiveId(liveDto.getId());
                List<LiveCpDto> liveCpDtos = liveCpMapper.toDto(list2);
                liveDto.setListCpDto(liveCpDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public List<LiveDto> queryAll(LiveQueryCriteria criteria) {
        criteria.setIsDelete(0);
        return liveMapper.toDto(liveRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public LiveDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(zb);
        } catch (Exception e) {

        }

        Live live = liveRepository.findById(id).orElseGet(Live::new);
        ValidationUtil.isNull(live.getId(), "Live", "id", id);

        //查询热度 +1
        Integer hot = live.getHot();
        live.setHot(hot + 1);
        Live save = liveRepository.save(live);
        LiveDto liveDto = liveMapper.toDto(save);
        String orgArea = liveDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            liveDto.setOrgAreas(array);
        } else {
            String[] array = {};
            liveDto.setOrgAreas(array);
        }
        List<LiveCp> list = liveCpRepository.findByLiveId(liveDto.getId());
        List<LiveCpDto> liveCpDtos = liveCpMapper.toDto(list);
        liveDto.setListCpDto(liveCpDtos);
        return liveDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public LiveDto create(LiveAddDto dto) {
        int flag = 0;
        Live resources = new Live();
        resources.setName(dto.getName());
        resources.setMan(dto.getMan());
        resources.setContextType(dto.getContextType());
        resources.setContext(dto.getContext());
        resources.setContextUrl(dto.getContextUrl());
        resources.setHot(0);
        resources.setType(dto.getType());
        resources.setPic(dto.getPic());
        resources.setStart(dto.getStart());
        resources.setEnd(dto.getEnd());
        resources.setStatus(dto.getStatus());
        if (dto.getSort() == null) {
            flag = -1;
            resources.setSort(0);
        } else {
            resources.setSort(dto.getSort());
        }
        resources.setIsDelete(0);
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        resources.setIsShow(dto.getIsShow());
        Live save = liveRepository.save(resources);
        if (flag == -1) {
            save.setSort(save.getId());
            Live save1 = liveRepository.save(save);
            return liveMapper.toDto(save1);
        } else {
            return liveMapper.toDto(save);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(LiveEditDto dto) {
        Live resources = liveRepository.findById(dto.getId()).orElseGet(Live::new);
        ValidationUtil.isNull(resources.getId(), "Live", "id", dto.getId());
        resources.setName(dto.getName());
        resources.setMan(dto.getMan());
        resources.setContextType(dto.getContextType());
        resources.setContext(dto.getContext());
        resources.setContextUrl(dto.getContextUrl());
        //resources.setHot(0);
        resources.setType(dto.getType());
        resources.setPic(dto.getPic());
        resources.setStart(dto.getStart());
        resources.setEnd(dto.getEnd());
        resources.setStatus(dto.getStatus());
        resources.setSort(dto.getSort());
        resources.setIsDelete(0);
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        resources.setIsShow(dto.getIsShow());
        liveRepository.save(resources);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //liveRepository.deleteById(id);
            Optional<Live> res = liveRepository.findById(id);
            if (res.isPresent()) {
                Live live = res.get();
                live.setIsDelete(1);
                liveRepository.save(live);
            }
        }
    }

    public void download(List<LiveDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LiveDto live : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("直播名称", live.getName());
            map.put("封面", live.getPic());
            map.put("主讲人", live.getMan());
            map.put("开始时间", live.getStart());
            map.put("结束时间", live.getEnd());
            map.put("直播状态", live.getStatus());
            map.put("直播类型", live.getType());
            map.put("h5是否展示   默认否", live.getIsShow());
            map.put("排序", live.getSort());
            map.put("地区组织机构区分  ", live.getOrgArea());
            map.put("是否假删除默认否", live.getIsDelete());
            map.put("热度", live.getHot());
            map.put("内容分类", live.getContextType());
            map.put("内容", live.getContext());
            map.put("内容链接", live.getContextUrl());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}